package org.net5ijy.cloud.plugin.feign.core.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.net5ijy.cloud.plugin.feign.core.util.ZipUtil.Text;

public class FileUtil {
  /**
   * zipTexts
   *
   * @param textList text集合
   * @param handler 输出流处理器
   * @author xuguofeng
   * @date 2020/11/16 15:58
   */
  public static void save(List<Text> textList, String basedir) {
    remove(basedir);
    String b = basedir + "/src/main/java";
    new File(b).mkdirs();
    
    for (Text textFile : textList) {
      FileOutputStream fos = null;
      try {
        File f = null;
        if ("pom.xml".equals(textFile.getFileName())) {
          f = new File(basedir + "/" + textFile.getFileName());
        } else {
          f = new File(b + "/" + textFile.getFileName());
        }
        f.getParentFile().mkdirs();
        f.createNewFile();
        fos = new FileOutputStream(f);
        fos.write(textFile.getText().getBytes());
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  
  static void remove(String path) {
    File f = new File(path);
    if (!f.exists()) {
      return;
    }
    if (f.isDirectory()) {
      File[] fList = f.listFiles();
      for (File f1 : fList) {
        remove(f1.getPath());
      }
      f.delete();
    } else {
      f.delete();
    }
  }
}
